<template>
  <div class="app-container">
    <el-card :body-style="{ 'padding-left': '40px' }">
      <el-form
        ref="queryForm"
        :model="form"
        label-position="top"
        label-width="100px"
        label-suffix=":"
        :rules="rules"
      >
        <dk-form :form-input="formList" :span-num="1" :rule-form="form" />
        <Piece
          ref="piece"
          :tableBodyList.sync="tableBodyList"
          :billingMethod="form.billingMethod"
        ></Piece>
      </el-form>

      <div style="margin-top: 80px; text-align: right">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
// 接口api：first step
// import Weight from "./table/weight.vue";
import Piece from './table/piece.vue';
import {
  freightTemplateAdd,
  freightTemplateDetail,
  freightTemplateUpdate,
} from '@/api/list/freight-template.js';

export default {
  data() {
    return {
      tableBodyList: [],
      // 表单对象：two step
      form: {
        templateName: '',
        id: undefined,
        // 商品类别，1:店铺商品，2：会员服务，3：自营商品
        type: 1,
        billingMethod: 1,
        canArea: 0,
        firstWeight: 0,
        freightFee: 0,
        conWeight: 0,
        conFee: 0,
        brandId: 0,
      },
      // 表单配置项：three step
      formList: [
        {
          label: '模板名称',
          placeholder: '请输入',
          type: 'input',
          name: 'templateName',
          prop: 'templateName',
          maxlength: 10,
        },

        {
          label: '模板类型',
          placeholder: '请选择',
          type: 'radio',
          name: 'type',
          prop: 'type',
          list: [
            { name: '买家承担运费', value: 0 },
            { name: '卖家包邮', value: 1 },
          ],
        },
        {
          label: '计费方式',
          placeholder: '请选择',
          type: 'radio',
          name: 'billingMethod',
          prop: 'billingMethod',
          list: [
            { name: '件数', value: 0 },
            { name: '重量', value: 1 },
          ],
        },
      ],
      // 校验对象：four step
      rules: {
        templateName: [
          { required: true, message: '请输入名称', trigger: 'change' },
        ],
        type: [
          { required: true, message: '请选择模板类型', trigger: 'change' },
        ],
        billingMethod: [
          { required: true, message: '请选择计费方式', trigger: 'change' },
        ],
        // areaFreight: [
        // { required: true, message: "请选择计费方式", trigger: "change" },
        // ],
      },
      // 接口存储对象：five step
      interfaceObj: {
        // provApiName: getProvince,
        addApiName: freightTemplateAdd,
        editApiName: freightTemplateUpdate,
        detApiName: freightTemplateDetail,
      },
    };
  },
  created() {
    const { uuid = '' } = this.$route.params;
    if (uuid) {
      this.form.id = uuid;
      this.loading = true;
      this.$nextTick(async () => {
        await this.network().getDetail();
      });
    }
  },
  methods: {
    // handleCity(val) {
    //   let value = val.join("");
    //   if(value){
    //     let res = this.getProvData.find((item) => item.name === value);
    //     this.network().getCities(res.codeP)
    //   }
    // },
    // handleArea(val){
    //   let value = val.join("");
    //   if(value){
    //     let res = this.getCityData.find((item) => item.name === value);
    //     this.network().getArea(res.codeC)
    //   }

    // },

    // 删除配送区域
    delArea() {
      this.$confirm('是否删除已选中的地区?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (this.from.billingMethod == 1) {
            this.picCheckedArea = '';
            this.picCheckedCities = '';
            this.picCheckedCountry = '';
          } else {
            this.checkedArea = '';
            this.checkedCities = '';
            this.checkedCountry = '';
          }
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },

    cancel() {
      this.$router.go(-1);
    },
    submit() {
      const throttleStatus = this.throttle(); // 节流
      if (!throttleStatus) return;
      this.$refs['queryForm'].validate((valid) => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.network().editForm();
          } else {
            this.network().addForm();
          }
        }
      });
    },
    network() {
      return {
        // 详情
        getDetail: async () => {
          const { detApiName } = this.interfaceObj;
          const { data } = await detApiName(this.form.id);
          if (data) {
            Object.assign(this.form, data);
          }

          console.log(data.freightTemplateAreaVo);
          if (data.freightTemplateAreaVo) {
            // 遍历 freightTemplateAreaVo 数组
            for (let i = 0; i < data.freightTemplateAreaVo.length; i++) {
              // 创建一个新的对象
              let obj = {
                id: i + 1,
                picCanArea:
                  JSON.parse(data.freightTemplateAreaVo[i].picCanArea) || [],
                first: data.freightTemplateAreaVo[i].first,
                firstFee: data.freightTemplateAreaVo[i].firstFee,
                second: data.freightTemplateAreaVo[i].second,
                secondFee: data.freightTemplateAreaVo[i].secondFee,
              };
              console.log(obj);
              // 将新的对象推送到 this.tableBodyList 中
              this.tableBodyList.push(obj);
            }
          }
          // if (data.freightTemplateAreaVo) {
          //   // 遍历 freightTemplateAreaVo 数组
          //   for (let i = 0; i < data.freightTemplateAreaVo.length; i++) {
          //     // 创建一个新的对象
          //     let obj = {
          //       first: data.freightTemplateAreaVo[i].first,
          //       firstFee: data.freightTemplateAreaVo[i].firstFee,
          //       second: data.freightTemplateAreaVo[i].second,
          //       secondFee: data.freightTemplateAreaVo[i].secondFee,
          //       codeArea: data.freightTemplateAreaVo[i].codeArea,
          //       codeCity: data.freightTemplateAreaVo[i].codeCity,
          //       codeProvince: data.freightTemplateAreaVo[i].codeProvince,
          //       nameArea: data.freightTemplateAreaVo[i].nameArea,
          //       nameCity: data.freightTemplateAreaVo[i].nameCity,
          //       nameProvince: data.freightTemplateAreaVo[i].nameProvince,
          //     };
          //     // 将新的对象推送到 this.tableBodyList 中
          //     this.tableBodyList.push(obj);
          //   }
          // }
        },
        // 新增
        addForm: async () => {
          const freightTemplateAreaVo =
            this.$refs.piece.freightTemplateAreaVo.map((item) => {
              return {
                isDelete: 0,
                ...item,
              };
            });
          const obj = {
            ...this.form,
            freightTemplateAreaVo,
            createBy: this.$store.state.user.name,
          };
          const { addApiName } = this.interfaceObj;
          const { code } = await addApiName(obj);
          if (code === 0) {
            this.$modal.msgSuccess('新增成功');
            this.resetForm('queryForm');
            this.$router.go(-1);
          }
        },
        // 编辑
        editForm: async () => {
          const freightTemplateAreaVo =
            this.$refs.piece.freightTemplateAreaVo.map((item) => {
              console.log(item);
              return {
                isDelete: 0,
                ...item,
              };
            });
          const obj = {
            ...this.form,
            freightTemplateAreaVo,
            updateBy: this.$store.state.user.name,
          };
          const { editApiName } = this.interfaceObj;
          const { code } = await editApiName(obj);
          if (code === 0) {
            this.$modal.msgSuccess('编辑成功');
            this.resetForm('queryForm');
            this.$router.go(-1);
          }
        },
      };
    },
  },
  components: {
    Piece,
  },
};
</script>
